import { useEffect, useState } from 'react'
import { NavBar, Toast } from 'antd-mobile'
import { useNavigate, useLocation } from 'react-router-dom'
import { Location,Arrow } from '@react-vant/icons';
import styles from './addcode.module.scss'
import img from '../../assets/aaa.png'
import { getaddAddressList, getDefaultAddress, type AddressData } from '../../api/ressService'
import {selectSelectedItems}from'../../store/cartSlice'
import { useAppSelector } from '../../store/store'
import mkf from '../../assets/mkf.png'
import { geCode,getPay, type CodeList } from '../../api/ressService'
import dayjs from 'dayjs'
import type { CartItem } from '../../store/cartSlice'
const Index = () => {
  const nav = useNavigate()
  const location = useLocation() //获取路由状态，用于接受从地址页那里选择的地址id
  const [selectedress, serSelectderess] = useState<AddressData | null>(null) //当前选中的地址
  const [loading, setLoading] = useState(true)
  const [codeList, setCodeList] = useState<CodeList | null>(null)
  
  // 检查是否从订单列表跳转过来
  const isFromOrderList = location.state?.fromOrderList
  const orderCartItems = location.state?.cartItems as CartItem[] | undefined
  const orderAddressInfo = location.state?.addressInfo
  
  // 根据来源决定使用哪个数据源
  const items = isFromOrderList ? (orderCartItems || []) : useAppSelector(selectSelectedItems)

  //获取地址数据并可以选择默认地址
  const getAddressData = async () => {
    setLoading(true)
    try {
      // 如果从订单列表跳转过来，直接使用订单中的地址信息
      if (isFromOrderList && orderAddressInfo) {
        serSelectderess(orderAddressInfo)
        setLoading(false)
        return
      }
      
      //获取所有地址存放在allAddresses里
      const res = await getaddAddressList()
      const allAddresses: AddressData[] = res.data || []
      console.log('所有地址列表', allAddresses);
      //检查是否有从地址列表返回的地址id
      const selectdeState = location.state?.selectdeId as string | undefined

      if (selectdeState) {
        const founAddress = allAddresses.find(addr => addr.id === selectdeState)
        if (founAddress) {
          serSelectderess(founAddress)
          console.log('用户选择的地址', founAddress);
        }
        else {
          //如果找不到，比如地址已删除或者数据不同步，退回默认逻辑
          const defaultAddr = getDefaultAddress(allAddresses)
          serSelectderess(defaultAddr)
          Toast.show({
            content: '选中的地址不存在，已为您选择默认地址',
            position: 'bottom'
          })
        }
      } else {
        //否则，使用默认地址
        const defaultAddr = getDefaultAddress(allAddresses)
        serSelectderess(defaultAddr)
        console.log('默认地址', defaultAddr);

      }
    } catch (error) {
      console.error('地址错误', error)
      Toast.show({
        content: '获取地址错误，请稍后再试',
        position: 'bottom'
      })
      serSelectderess(null)
    }
    finally {
      setLoading(false)
    }
  }
  useEffect(() => {
    getAddressData()
  }, [location.state?.selectdeId, isFromOrderList, orderAddressInfo])
  //点击跳转到地址页面选择地址
const habdelSelectaddress=()=>{
  nav('/address',{state:{fromOrderPage:true}})
}
const handlePay=async()=>{
  const res=await geCode({
    createTime:dayjs().format('YYYY-MM-DD HH:mm:ss'),
    goods: items,
    address: selectedress ?? {},
    totalPrice: items.reduce((sum, it) => sum + Number(it.price) * it.quantity, 0)
  })
  setCodeList(res)
  console.log(res.data);
  const payRes=await getPay({
    id:String(res.data[0].id),
    returnUrl:'http://localhost:5173/'
  })
  console.log(payRes);
  if(payRes.code===200){
    window.location.href=payRes.data
  }
}
  


  return (
    <div className={styles.orderbox}>
      {/* 顶部导航栏 */}
      <NavBar onBack={() => nav(-1)} className={styles.anv}>下单</NavBar>
      {/* 收货地址区域（可点击去地址列表选择） */}
      <div className={styles.ressbox} onClick={habdelSelectaddress}>
        <div className={styles.ressIcon} >
          <Location />
        </div>
        {
          loading ? (
            <div>
              加载地址消息中...
            </div>
          ) : selectedress ? (
            <div className={styles.ressitem}>
              <div>
                <p>
                  <strong className={styles.ressname}>{selectedress.nickname}</strong>
                  <strong>{selectedress.tel}</strong>
                </p>
                <p>
                  {selectedress.provice_city_area} {selectedress.detail_address}
                </p>
                {
                selectedress.delivery && (
                  <span>
                    默认地址
                  </span>
                )
              }
              </div>
              <span className={styles.ressitembtn} >
               <Arrow  /> 
              </span>

            </div>
          ):(
            <div>
             <p>
                暂无收货地址，请先添加
              </p>
              <div className={styles.ressitembtn} onClick={() => nav('/addAddress/false')}>
               <span>去添加地址</span> <Arrow/>
              </div>
            </div>
          )
        }
      </div>
       {/* 地址与商品清单之间的分割线图片 */}
       <div className={styles.ressimg}>
          <img src={img} alt="" />
        </div>
        {/* 商品清单区域 */}
        <div className={styles.cartbox}>
          {/* 店铺头部：店铺名 + 认证徽标 */}
          <div className={styles.shopHeader}>
            <span className={styles.shopName}>益丰大药房</span>
            <span className={styles.shopBadge}>认证药房</span>
          </div>

          {/* 商品行：左侧标题，右侧价格；下一行展示数量 */}
          {items.map(item => (
            <div className={styles.itemBlock} key={item.shopSpuId}>
              <div className={styles.skuRow}>
                <span className={styles.skuTitle}>{item.title}</span>
                <span className={styles.skuPrice}>¥{Number(item.price).toFixed(1)}</span>
              </div>
              <div className={styles.qtyRow}>
                <span className={styles.qtyText}>x {item.quantity}</span>
              </div>
            </div>
          ))}

          {/* 运费行：右侧显示价格（此处为 0） */}
          <div className={styles.feeRow}>
            <span className={styles.feeLabel}>运费</span>
            <span className={styles.feeValue}>¥0</span>
          </div>

          {/* 底部小计：共 N 件商品 + 小计金额 */}
          <div className={styles.summaryRow}>
            {(() => {
              // 计算商品总件数
              const count = items.reduce((sum, it) => sum + it.quantity, 0)
              // 计算总金额（价格 * 数量）
              const total = items.reduce((sum, it) => sum + Number(it.price) * it.quantity, 0)
              return (
                <>
                  <span className={styles.summaryCount}>共{count}件商品</span>
                  <span className={styles.summaryLabel}>小计：</span>
                  <span className={styles.summaryTotal}>¥{total.toFixed(2)}</span>
                </>
              )
            })()}
          </div>
        </div>
        {/* 底部结算区域：联系客服 | 合计 | 去支付 */}
        <div className={styles.checkoutBar}>
          {/* 联系客服 */}
          <div className={styles.service}>
            <div className={styles.serviceIcon}><img src={mkf} alt="" /></div>
            <span>联系客服</span>
          </div>

          {/* 合计（整数与小数分开） */}
          {(() => {
            const total = items.reduce((sum, it) => sum + Number(it.price) * it.quantity, 0)
            const [intPart, fracPart = '00'] = total.toFixed(2).split('.')
            return (
              <div className={styles.totalBox}>
                <span className={styles.totalLabel}>合计：</span>
                <span className={styles.totalCurrency}>¥</span>
                <span className={styles.totalInt}>{intPart}</span>
                <span className={styles.totalFrac}>.{fracPart}</span>
              </div>
            )
          })()}

          {/* 去支付按钮 */}
          <button className={styles.payBtn} onClick={handlePay}>去支付</button>
        </div>



    </div>
  )
}

export default Index
